package com.education.websocket.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.education.websocket.config.ServerEncoder;
import com.education.websocket.data.HomeBuffer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: liftsail
 * @Date: 2022/10/14 14:36
 * @Description: 不积跬步无以至千里
 * websocket的处理类(服务器)
 */
@Slf4j
@Component(value = "WebSocketServerWELCO")
@ServerEndpoint(value = "/welco/home/pushMessage/{userId}", encoders = {ServerEncoder.class})
public class WebSocketServerWELCO {

    private static HomeBuffer homeBuffer;

    @Autowired
    public void setHomeBuffer(HomeBuffer homeBuffer) {
        WebSocketServerWELCO.homeBuffer = homeBuffer;
    }

    //业务中调用websocket发送实时信息
    //WebSocketServerWELCO.sendInfo(info.getContentText(), info.getToUserId().toString());

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServerWELCO> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 发送者userId
     */
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId, this);
        } else {
            //加入set中
            webSocketMap.put(userId, this);
            //在线数加1
            addOnlineCount();
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        //建立连接时初始化数据 老师id
        Object data = homeBuffer.data(userId);
        sendMessageObject(data);
        //sendMessage("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息接收并转发
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(message);
                } else {
                    //否则不在这个服务器上，发送到mysql或者redis
                    log.error("请求的userId:" + toUserId + "不在该服务器上");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送-String
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现服务器主动推送-Object
     */
    public void sendMessageObject(Object object) {
        try {
            this.session.getBasicRemote().sendObject(object);
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定义消息(供系统业务调用)
     * 静态方法
     *
     * @param sendData
     * @param userId
     */
    public static void sendInfo(Object sendData, String userId) {
        //log.info("发送消息到:" + userId + "，报文:" + sendData);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            //webSocketMap.get(userId).sendMessage(message);//字符文本
            /*CodesInfo codesInfo = new CodesInfo();
            codesInfo.setContentText("你最近还好吗？");
            codesInfo.setToUserId(5);
            List<Object> arrayList = new ArrayList<>();
            arrayList.add(codesInfo);*/
            webSocketMap.get(userId).sendMessageObject(sendData);//对象
        } else {
            log.error("用户" + userId + ",当前时刻不在线！");
        }
    }

    /*socket方法调用
    UserInfo userInfo = jwtUtil.getInfoFromToken();
    WebSocketServerWELCO.sendInfo(sds, userInfo.getId().toString());*/

    /**
     * 获得此时的在线人数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketServerWELCO.onlineCount++;
    }

    /**
     * 在线人数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServerWELCO.onlineCount--;
    }

}
